﻿using System;
using System.Collections;
using System.ComponentModel;
using System.Data;
using System.Data.SqlClient;
using System.Drawing;
using System.Web;
using System.Web.SessionState;
using System.Web.UI;

using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;
using SpringWaterDataAccess;
using Utilities;
using System.Web.Security;
using System.Xml;
using System.Globalization;

namespace sow
{
	/// <summary>
	/// Summary description for index.
	/// </summary>
    public partial class index : System.Web.UI.Page
	{
		protected System.Web.UI.HtmlControls.HtmlImage img30;
		protected System.Web.UI.HtmlControls.HtmlImage img31;
		protected System.Web.UI.HtmlControls.HtmlImage img32;
		protected System.Web.UI.HtmlControls.HtmlImage img33;
		protected System.Web.UI.HtmlControls.HtmlImage img34;
		protected System.Web.UI.HtmlControls.HtmlTable table76;
		protected System.Web.UI.WebControls.Repeater Repeater3;
		protected System.Web.UI.WebControls.Image Image1;
		protected System.Web.UI.HtmlControls.HtmlImage img36;

		public static int USER_ARTICLES_PUBLISH = 168;
		public static int USER_ATTICLES_PRAYER_DAILY = 169;
	    public static int USER_ATTICLES_QUESTION_ANSWER = 134;
		public static int USER_ATTICLES_BIBLE_BASICS = 170;
	
        private bool registerFlag = false;
        private CacheHelper cacheHelper = new CacheHelper();
		protected void Page_Load(object sender, System.EventArgs e)
		{

            Page.RegisterStartupScript("SetFocus", "<script>document.getElementById('" + Textbox1.ClientID + "').focus();</script>");
			HttpCookie nameCookie = Request.Cookies["NickName"];
            HttpCookie encodingCookie = Request.Cookies["IsEncoded"];
			string message = Request.QueryString["message"];

			//logoutButton.Visible = false;
			
			if (message != null) 
			{
				InfoLabel.Text=message;
			} else 	if (nameCookie == null) 
			{
				InfoLabel.Text="";
			} else {


                //logoutButton.Visible = true;
                if (encodingCookie != null && encodingCookie.Value == "True")
                {
                    string userName = HttpUtility.UrlDecode(nameCookie.Value);
                    InfoLabel.Text = userName + "，你已成功登录!";
                    //If the user name is 'publish', we need to clean up cache, and always load DB
                    if (userName == "publish")
                    {
                        cacheHelper.CleanAllCache();
                    }
                } else {
                    InfoLabel.Text = nameCookie.Value + "，你已成功登录!";
                }

                registerFlag = false;
			}

			if (!IsPostBack) 
			{
				BindDataForRepeater();
//				this.Button2.Attributes["onclick"] = "if(document.all('Textbox1').value=='') return false; location.href='../search/keysearch.aspx?key=' + encodeURI(document.all('Textbox1').value);return false;";
			}
		}

		public string StrConv(string strIn, string encoding)
		{
			return System.Web.HttpUtility.UrlEncode(strIn,
				            System.Text.Encoding.GetEncoding(encoding));
		}

		private void BindDataForRepeater()
		{
     		SQLAccess sql = new SQLAccess();
     		ForumDataAccess fd = new ForumDataAccess();
			int totals;
			string forumID;

            // DISK
            Repeater1.DataSource = cacheHelper.DiskDS;
            Repeater1.DataBind();

            // 日日得胜
            Repeater20.DataSource = cacheHelper.VictoryDS;
			Repeater20.DataBind();

            // Headline
            Repeater18.DataSource = cacheHelper.HeadlineDS; 
			Repeater18.DataBind();


            // Thology and Thinking
            Repeater15.DataSource = cacheHelper.ThinkingDS;
			Repeater15.DataBind();

			//福音小品
            Repeater13.DataSource = cacheHelper.GospelDS;
			Repeater13.DataBind();


            // 最新视频
            Repeater12.DataSource = cacheHelper.VideoDS; 
			Repeater12.DataBind();

			// The article for Q/A only exists on sunday
			//DateTime sunday = DateTime.Now.AddDays(System.Convert.ToDouble(DateTime.Now.DayOfWeek) * (-1) );
			//DataList2.DataSource = fd.getPosts(USER_ATTICLES_QUESTION_ANSWER,DateTime.Now.Year,
			//	  sunday.Month,sunday.Day,
			//	1,1,out totals,"blog","Active",0,"CreateDate");

            //讲道 - 哥林多后书
            Repeater14.DataSource = cacheHelper.CorinthiansDS;
			Repeater14.DataBind();

            //  文摘网站排行榜
            DataList1.DataSource = cacheHelper.PartnersDS;
			DataList1.DataBind();

			// The article for bible basics only exists the first day of each month
			/*DataList3.DataSource = fd.getPosts(USER_ATTICLES_BIBLE_BASICS,DateTime.Now.Year,DateTime.Now.Month,0,
				1,1,out totals,"blog","Active",0,"CreateDate");
			DataList3.DataBind();*/

			
			// This is the account for all the articles to be published on homepage
			int categoryID = Convert.ToUInt16(Request.QueryString["CategoryID"]);

		    // 圣经真道
            Repeater2.DataSource = cacheHelper.GetChchedDSByCategory(33);
			Repeater2.DataBind();

            Repeater4.DataSource = cacheHelper.GetChchedDSByCategory(34);
			Repeater4.DataBind();

            Repeater5.DataSource = cacheHelper.GetChchedDSByCategory(35);
			Repeater5.DataBind();

            Repeater6.DataSource = cacheHelper.GetChchedDSByCategory(37);
			Repeater6.DataBind();

            Repeater7.DataSource = cacheHelper.GetChchedDSByCategory(36);
			Repeater7.DataBind();

            Repeater8.DataSource = cacheHelper.GetChchedDSByCategory(38);
			Repeater8.DataBind();

            Repeater10.DataSource = cacheHelper.GetChchedDSByCategory(39);
			Repeater10.DataBind();

            Repeater11.DataSource = cacheHelper.GetChchedDSByCategory(44);
			Repeater11.DataBind();

            Repeater9.DataSource = cacheHelper.NewPublishDS;
			Repeater9.DataBind();

            // 最新诗歌
            //Repeater16.DataSource = cacheHelper.NewSongDS;
			//Repeater16.DataBind();
			
			// Top 10 articles for the current  month
			/**DataSet ds1 = fd.getPosts(USER_ARTICLES_PUBLISH,DateTime.Now.Year,
			DateTime.Now.Month,0,
				1,10,out totals,"","",0,"NumberOfVisits desc");
			Repeater1.DataSource = ds1.Tables[0].DefaultView;
			Repeater1.DataBind();**/
    	}

		private string GetPrayerForChinaToday()
		{
			String URLString = "http://216.19.205.28/p4china/guest.asp";
	
			XmlDocument xmlDocContinents = new XmlDocument();

			XmlNode node = null;
			try 
			{
				xmlDocContinents.Load(URLString);
			
				DateTime today = DateTime.Now;
        
				node = xmlDocContinents.SelectSingleNode("/prayforchina/daily/chinese/items"); 
				//xmlDocContinents.SelectSingleNode("/prayforchina/daily/chinese[date='" + 
				//today.ToString("yyyy-m-d") + "']/items");
			}	
			catch (Exception ex) 
			{
				return "";
			}


			if (node == null)
				return "";
			else
				return node.InnerText;
		}  

		public string getCategoryFromID(string ID)
		{
			return Helper.getCategoryFromID(ID);
		}

		public string getURLFromCategoryID(object categoryID) 
		{ 

			return Helper.getLocationFromCategory(System.Convert.ToString(categoryID));
		}
		
	
		#region Web Form Designer generated code
		override protected void OnInit(EventArgs e)
		{
			//
			// CODEGEN: This call is required by the ASP.NET Web Form Designer.
			//
			InitializeComponent();
			base.OnInit(e);
		}
		
		/// <summary>
		/// Required method for Designer support - do not modify
		/// the contents of this method with the code editor.
		/// </summary>
		private void InitializeComponent()
		{    

		}
		#endregion

		private void MyRepeater_ItemCommand(object source, System.Web.UI.WebControls.RepeaterCommandEventArgs e)
		{
		
		}

	
		private void Repeater1_ItemCommand(object source, System.Web.UI.WebControls.RepeaterCommandEventArgs e)
		{
		
		}

		private void Button2_ServerClick(object sender, System.EventArgs e)
		{
		
		}

		private void logoutButton_Click(object sender, System.EventArgs e)
		{
			//Response.Cookies.Clear();

			// The Clear() method does not work for some reson.
			// The following code is Hack from google!
			HttpCookie objCookie= new HttpCookie("NickName");
			objCookie.Expires = DateTime.Today.AddYears(-1);
			Response.AppendCookie(objCookie); 

			objCookie= new HttpCookie("Email");
			objCookie.Expires = DateTime.Today.AddYears(-1);
			Response.AppendCookie(objCookie); 

			//Response.Write("logout<br>");
			Response.Redirect("index.aspx");				
		}

		private void REPEATER2_ItemCommand(object source, System.Web.UI.WebControls.RepeaterCommandEventArgs e)
		{
		
		}

		private void Repeater3_ItemCommand(object source, System.Web.UI.WebControls.RepeaterCommandEventArgs e)
		{
		
		}
	
		private void Search_Click(object sender, System.EventArgs e)
		{
			Button7_Click(sender, e);
	    }

		private void LinkButton1_Click(object sender, System.EventArgs e)
		{
			Response.Redirect("../search/ssearch.aspx");
		}

		private void Linkbutton4_Click(object sender, System.EventArgs e)
		{
			Response.Redirect("../search/ssearch.aspx");
		}

		private void LinkButton2_Click(object sender, System.EventArgs e)
		{
			Response.Redirect("forumsStart.aspx");
		}

		protected void Button2_Click(object sender, System.EventArgs e)
		{
			Button7_Click(sender, e);
	    }

		private void Textbox1_TextChanged(object sender, System.EventArgs e)
		{
		
		}

		private void Linkbutton3_Click(object sender, System.EventArgs e)
		{
			Response.Redirect("../../bibletool/ReadBible.aspx");
		}

		private void DataList4_SelectedIndexChanged(object sender, System.EventArgs e)
		{
		
		}

		protected void Button1_Click(object sender, System.EventArgs e)
		{
			Response.Redirect("../../bibletool/ReadBible.aspx");
		}

		protected void Button4_Click(object sender, System.EventArgs e)
		{
			Response.Redirect("http://www.audiotreasure.com/mp3/Mandarin/menu.htm");
		}

		protected void Button5_Click(object sender, System.EventArgs e)
		{
            ForumDataAccess fd = new ForumDataAccess();

            int totals;

            // Stream of deserts account
            DataSet streamDS = fd.getPosts(79, 2005,
                DateTime.Now.Month, DateTime.Now.Day,
                1, 1, out totals, "", "Active", 43, "CreateDate");

            Response.Redirect("bloggerweb.aspx?UserID=79&postID=" +
                Convert.ToString(streamDS.Tables[0].Rows[0]["PostID"]));
		}

		protected void Button7_Click(object sender, System.EventArgs e)
		{
			if(this.Textbox1.Text.Trim() != "") 
			{
				Session["searchkey"] = this.Textbox1.Text.Trim();
				string searchKey = Textbox1.Text.Trim();
				if (Convert.ToInt16(RadioButtonList1.SelectedValue) == 1) 
				{
                     
					 Response.Redirect("../../bibletool/ReadBible.aspx?Keyword=" 
						 + searchKey + "&AndOr=AND"  + "&Search=Submit+Query");
				} 
				else 
				{
					Response.Redirect("../search/keysearch.aspx?key=" + Server.HtmlEncode(this.Textbox1.Text.Trim()));
				}
			} 
			else 
			{

				// Bible search button clicked.
				//if (Keyword.Text != null && Keyword.Text != "") 
				//{
				//	string logic = RadioOR.Checked ? "OR" : "AND";
				//	Response.Redirect("../bibletool/ReadBible.aspx?Keyword=" 
				//		+ Keyword.Text + "&AndOr=" + logic + "&Search=Submit+Query");
				//}

				try 
				{
					UserObject u = 
						UserObject.LoginOn(Textbox9.Value,idPassword.Value);

					if (null != u) // login succeed
					{
						HttpCookie encodingCookie = new HttpCookie("IsEncoded", "True");
                        Response.Cookies.Add(encodingCookie);
                        encodingCookie.Expires = DateTime.MaxValue;
                        					    
                        string nick = HttpUtility.UrlEncode(u.NickName);
                        HttpCookie userNickNameCookie = new HttpCookie("NickName", nick);
                        userNickNameCookie.Expires = DateTime.MaxValue;
	                    
						Response.Cookies.Add(userNickNameCookie);
						
                        HttpCookie userEmailCookie = new HttpCookie("Email", u.Email);
						userEmailCookie.Expires = DateTime.MaxValue;	
						Response.Cookies.Add(userEmailCookie);

                    	// force to refresh. Hack! has to be a better way
						Response.Redirect("index.aspx");
						//FormsAuthentication.RedirectFromLoginPage(idEmail.Value,true);
					 
					}
					else
					{
						InfoLabel.Text = "对不起,登录错误! 如果你还没有注册登记，请先注册登记，再你的密码登录！";
					
						// stay on the same page and display login fail error
					}
				} 
				catch (Exception ex) 
				{
					InfoLabel.Text = "对不起,登录错误! 如果你还没有注册登记，请先注册登记，再用你的密码登录！";
				}
			}
		}

        protected void Button6_Click(object sender, EventArgs e)
        {
            Response.Redirect("http://www.quanyuan.org");
        }
        protected void Button8_Click(object sender, EventArgs e)
        {
            Response.Redirect("http://www.quanyuan.org/spaceindex.aspx");
        }
        protected void Button9_Click(object sender, EventArgs e)
        {
            //Response.Redirect("mailto:contact@springofwater.net");
            Response.Redirect("userinput.aspx");
        }
        protected void LinkButton1_Click1(object sender, EventArgs e)
        {
            ForumDataAccess fd = new ForumDataAccess();

            int totals;

            // Stream of deserts account
            DataSet streamDS = fd.getPosts(79, 2005,
                DateTime.Now.Month, DateTime.Now.Day,
                1, 1, out totals, "", "Active", 43, "CreateDate");            

            Response.Redirect("bloggerweb.aspx?UserID=79&postID=" + 
                Convert.ToString(streamDS.Tables[0].Rows[0]["PostID"]));
        }

        protected void Repeater1_ItemCommand1(object source, RepeaterCommandEventArgs e)
        {

        }
}
}
